"""
Power by newmean
Email: ywwg@qq.com
"""

import logging
import requests
from datetime import timedelta
import voluptuous as vol

from homeassistant.components.device_tracker import (
    PLATFORM_SCHEMA, SOURCE_TYPE_GPS)
from homeassistant.const import (CONF_USERNAME, CONF_PASSWORD, CONF_CLIENT_ID, CONF_NAME)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import track_time_interval
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import Throttle

_LOGGER = logging.getLogger(__name__)
UPDATE_INTERVAL = timedelta(seconds=15)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_NAME): cv.string,
    vol.Required(CONF_USERNAME): cv.string,
    vol.Required(CONF_PASSWORD): cv.string,
    vol.Required(CONF_CLIENT_ID): cv.string
})


def setup_scanner(hass, config: ConfigType, see, discovery_info=None):
    TuQiangTrackDeviceTracker(hass, config, see)
    return True


class TuQiangTrackDeviceTracker(object):
    def __init__(self, hass, config: ConfigType, see) -> None:
        self.hass = hass
        self.name = config[CONF_NAME]
        self.username = config[CONF_USERNAME]
        self.password = config[CONF_PASSWORD]
        self.devices = config[CONF_CLIENT_ID]
        self.see = see
        self.session = requests.session()
        self.host = 'http://www.tuqiangol.com'
        self.userid = None
        self.usertype = None
        if not self._login(self.username, self.password):
            _LOGGER.warning('途强：登陆失败，用户名或密码错误。')
        self._update_info()
        track_time_interval(hass, self._update_info, UPDATE_INTERVAL)

    def __encode(self, code):
        en_code = ''
        for s in code:
            en_code = en_code + str(ord(s)) + '|'
        return en_code[:-1]

    def _login(self, username, password):
        p_data = {
            'ver': '1',
            'method': 'login',
            'account': username,
            'password': self.__encode(password),
            'language': 'zh'
        }
        url = self.host + '/api/regdc'
        response = self.session.post(url, p_data)
        if response.json()['code'] == 0:
            self.__get_userid()
            return True
        else:
            return False

    def __get_userid(self):
        url = self.host + '/customer/getProviderList'
        resp = self.session.post(url, data=None).json()
        self.userid = resp['data']['user']['userId']
        self.usertype = resp['data']['user']['type']

    def _get_device_info(self, imei_sn):
        if self.userid is None or self.usertype is None:
            self._login(self.username, self.password)
        else:
            url = self.host + '/console/refresh'
            p_data = {
                'choiceUserId': self.userid,
                'normalImeis': str(imei_sn),
                'userType': self.usertype,
                'followImeis': '',
                'userId': self.userid,
                'stock': '2'
            }
            resp = self.session.post(url, p_data)
            return resp.json()['data']['normalList'][0]

    @Throttle(UPDATE_INTERVAL)
    def _update_info(self, now=None):
        """Update the device info."""
        _LOGGER.debug("Updating devices %s", now)
        data = self._get_device_info(self.devices)
        lat = float(data['lat'])
        lon = float(data['lng'])
        battery = float(data['voltage'])
        accuracy = int(data['acc'])
        self.see(
            dev_id=self.name,
            gps=(lat, lon),
            source_type=SOURCE_TYPE_GPS,
            gps_accuracy=accuracy,
            battery=battery,
        )
        return True
